#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 数据库操作相关

from sqlalchemy.orm import Session
from fastapi import HTTPException
from .models import *
from .schemas import *
from .utils import *
from common.json_tools import resp_200, resp_400, response
from common.log import logger


def get_users_method(db: Session, skip: int = 0, limit: int = 10):
    return db.query(User).offset(skip).limit(limit).all()

def get_user_method(db: Session, uid: int):
    user = db.query(User).filter(User.id == uid).first()
    if not user:
        raise HTTPException(status_code=404, detail="user not exists")
    return user

def get_user_by_email(db: Session, email: str):
    user = db.query(User).filter(User.email == email).first()
    if not user:
        raise HTTPException(status_code=404, detail="user not exists")
    return user


def create_user_method(db: Session, user: UserModel):
    logger.info("创建用户开始了")
    db_user = db.query(User).filter(User.email == user.email).first()
    if db_user:
        logger.info(f"用户:{user.email}已经存在了！")
        # raise HTTPException(status_code=200, detail="this user already exists")
        return resp_400(data="this user already exists")
        # return response(code=1, message="error", data="this user already exists")
    # fake_hashed_password = user.password + "_hashed"
    hashed_password = get_password_hash(user.password)

    init_user = User(email=user.email, hashed_password=hashed_password)
    db.add(init_user)
    db.commit()
    db.refresh(init_user)
    # return init_user
    logger.info(f"创建用户{user.email}成功了")
    return resp_200(data={"user": init_user.email})


def get_items_method(db: Session, skip: int = 0, limit: int = 10):
    return db.query(Item).offset(skip).limit(limit).all()


def get_items_by_uid_method(db: Session, uid: int, skip: int = 0, limit: int = 10):
    user = db.query(User).filter(User.id == uid).first()
    if not user:
        raise HTTPException(status_code=200, detail="this user is not valid")
    return db.query(Item).filter(Item.owner == user).offset(skip).limit(limit).all()


def create_item_by_user_method(db: Session, uid: int, item: ItemModel):
    # 先查询uid用户是否存在
    get_user_method(db, uid)
    init_item = Item(**item.model_dump(), owner_id=uid)
    db.add(init_item)
    db.commit()
    db.refresh(init_item)
    return init_item
